#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include "implement.h"
/*
example:
  LFSR: x^60+x+1

  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t lfsr = 0b0000000000000000000000000000000000000000000000000000000000000011;//x^60
  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t ofst = 0b0000100000000000000000000000000000000000000000000000000000000000;//offset
  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t stat = 0b0000111111111100000000001111111111000000000011111111110000000000;//start value  
*/

int main(int argc, char *argv[])
{
  //LFSR: x^5+x^3+1
  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t lfsr = 0b0000000000000000000000000000000000000000000000000000000000001001;//x^5
  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t ofst = 0b0000000000000000000000000000000000000000000000000000000000010000;//offset
  //----------------6666555555555544444444443333333333222222222211111111110000000000
  //----------------3210987654321098765432109876543210987654321098765432109876543210
  uint64_t stat = 0b0000000000000000000000000000000000000000000000000000000000011000;//start value  
  if(argc > 2) {
    printf("Too many argument.\n");
    printf("Input format:\n");
    printf("./generate_LFSR <you need the length of output sequence>\n");
    exit(0);
  }
  uint64_t STRLEN;
  FILE *fp;//file pointer

  if((fp = fopen("sequence.txt", "w")) != NULL)
  {
    if(argc == 1) {//argv[1]
      printf("The length of the generated sequence is one period by default.\n");
      STRLEN = pow(2,deg(ofst)+1)-1; //The length of the generated sequence
      printf("STRLEN = %ld\n",STRLEN);
      fprintf(fp,"%ld\n",STRLEN);
    }
    else {
      STRLEN = atoi(argv[1]); //The length of the generated sequence
      printf("STRLEN = %ld\n",STRLEN);
      fprintf(fp,"%ld\n",STRLEN);
    }
    uint64_t *p=&stat,i;              //p -> start value
    int g;
    for(i=0; i<STRLEN; i++) {
      g = gen(lfsr,stat);           //generate the next bit
      printf("%ld",stat%2);
      fprintf(fp,"%ld ",stat%2);
      shift(p,ofst,g);              //shift the state of register
    }
    printf("\n");
  }
  else {
    printf("Can't write to sequence.txt .\n");
    exit(0);
  }
  if(fclose(fp) != 0)
    printf("Error in closing file %s\n", argv[1]);
}
